# -*- coding: utf-8 -*-
# article_info.py
# Created by Hardy on 26th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.

import heapq
import json

from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils


class ParaInfoQuerier(ElasticSearchQuerier):

    def __init__(self, es, index, doc_type, nlp_service=None):
        super(ParaInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type
        self.nlp_service = nlp_service

    def _build_query(self, args):
        ids = args.get('ids')
        if ids is None:
            raise ValueError('message: "ids"(list of "article_id") is needed')

        query = {"query": {"terms": {"article_id": ids}}, 'sort': {'paragraph_id': 'asc'}}
        return query, {}, {'ids': ids}

    def _build_result(self, es_result, param):
        ids = param['ids']
        articles = []
        for hit in es_result['hits']['hits']:
            data = self.extractResult(hit)
            articles.append((data.get('article_id'), data))
        article_dict = dict(articles)
        return {
            "infos": [article_dict.get(i, {}) for i in ids]
        }

    def extractResult(self, hit):
        source_ = hit['_source']

        return {
            'title': source_['title'],
            'url': source_['url'],
            'text': source_['text'],
            'prev_pic': source_['prev_pic'],
            'post_pic': source_['post_pic'],
            'article_id': source_['article_id']
        }
